package com.rcp.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


@WebServlet("/MenuCreation")
public class MenuCreation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Connection connection = Nexus.connection;
	
    public MenuCreation() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		
		//Access database, get Drinks, Side orders, Entrees, Main Course
		ArrayList<Entree> entrees = new ArrayList<Entree>();
		ArrayList<Side> sides = new ArrayList<Side>();
		ArrayList<Drink> drinks = new ArrayList<Drink>();
		
		try {
			//Get Entrees
			String preparedQuery = "SELECT EntreeID, Name, Cost FROM Entrees;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			
			ResultSet results = ps.executeQuery();
			
			while(results.next()){
				int id = results.getInt("entreeID");
				String name = results.getString("name");
				double cost = results.getDouble("cost");
				
				Entree e = new Entree(id, name, cost);
				
				entrees.add(e);	
			}
	
			//Get Sides
			preparedQuery = "SELECT SideID, Name, Price FROM Sides;";
			
			ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			
			results = ps.executeQuery();
			
			while(results.next()){
				int id = results.getInt("SideID");
				String name = results.getString("name");
				double cost = results.getDouble("price");
				
				Side s = new Side(id, name, cost);
				
				sides.add(s);	
			}
			
			//Get Drinks
			preparedQuery = "SELECT DrinkID, Name, Cost, Size FROM Drinks;";
			
			ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			
			results = ps.executeQuery();
			
			while(results.next()){
				int id = results.getInt("drinkID");
				String name = results.getString("name");
				double cost = results.getDouble("cost");
				String size = results.getString("size");
				
				Drink d = new Drink(id, name, cost, size);
				
				drinks.add(d);	
			}
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ArrayList<String> e = new ArrayList<String>();
		ArrayList<String> s = new ArrayList<String>();
		ArrayList<String> d = new ArrayList<String>();
		
		//Replicate as Strings
		for(int i = 0; i < entrees.size(); i++){
			e.add(entrees.get(i).getName());
		}
		for(int i = 0; i < sides.size(); i++){
			s.add(sides.get(i).getName());
		}
		for(int i = 0; i < drinks.size(); i++){
			d.add(drinks.get(i).getName());
		}
		
		//Store them in the request object as attributes
		request.getSession().setAttribute("entrees", entrees);
		request.getSession().setAttribute("sides", sides);
		request.getSession().setAttribute("drinks", drinks);
		
		request.getSession().setAttribute("e", e);
		request.getSession().setAttribute("s", s);
		request.getSession().setAttribute("d", d);
		
		//request.getRequestDispatcher("BuildMenu.jsp").forward(request, response);
		response.sendRedirect("BuildMenu.jsp");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		
		String[] entreesTmp = request.getParameterValues("entree");
		String[] sidesTmp = request.getParameterValues("side");
		String[] drinksTmp = request.getParameterValues("drink");
		String name = request.getParameter("menuName");
		
		int[] eField = new int[entreesTmp.length];
		int[] sField = new int[sidesTmp.length];
		int[] dField = new int[drinksTmp.length];
		
		//Fill int[] with field values
		for(int i = 0; i < eField.length; i++){
			if(entreesTmp[i].length() > 0){
				eField[i] = Integer.parseInt(entreesTmp[i]);
			}
			else{
				eField[i] = -1;
			}
		}
		
		for(int i = 0; i < sField.length; i++){
			if(sidesTmp[i].length() > 0){
				sField[i] = Integer.parseInt(sidesTmp[i]);
			}
			else{
				sField[i] = -1;
			}
		}

		for(int i = 0; i < dField.length; i++){
			if(drinksTmp[i].length() > 0){
				dField[i] = Integer.parseInt(drinksTmp[i]);
			}
			else{
				dField[i] = -1;
			}
		}
		
		//Get menu field pointers
		Menu menu = new Menu();
		
		LinkedHashMap<String, Integer> e = menu.getEntrees();
		LinkedHashMap<String, Integer> s = menu.getSides();
		LinkedHashMap<String, Integer> d = menu.getDrinks();
		menu.setName(name);
		
		//Get names of items
		ArrayList<String> entrees = (ArrayList<String>) request.getSession().getAttribute("e");
		ArrayList<String> sides = (ArrayList<String>) request.getSession().getAttribute("s");
		ArrayList<String> drinks = (ArrayList<String>) request.getSession().getAttribute("d");
		
		//Add Map to menu <item, quantity>
		for(int i = 0; i < entrees.size(); i++){
			if(eField[i] != -1){
				//System.out.println("Key: " + entrees.get(i) + "  Value: " + eField[i]);
				e.put(entrees.get(i), eField[i]);
			}
		}
				
		for(int i = 0; i < sides.size(); i++){
			if(sField[i] != -1){
				s.put(sides.get(i), sField[i]);
			}		
		}
		
		for(int i = 0; i < drinks.size(); i++){
			if(dField[i] != -1){
				d.put(drinks.get(i), dField[i]);
			}
		}
		
		int menuID = 0;
		
		//Add Menu to database
		try {
			String preparedQuery = 
					"INSERT INTO Menus(menu, menuName) " +
					"VALUES (?, ?);"; 
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setObject(1, menu);
			ps.setString(2, menu.getName());
			
			ps.executeUpdate();
			
			//Get AUTO_INCREMENT ID
			preparedQuery = "SELECT LAST_INSERT_ID();";
			ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ResultSet results = ps.executeQuery();
			
			results.first();
			menuID = results.getInt(1);

			//Get Menu Again
			preparedQuery = 
					"SELECT menu FROM Menus WHERE menuID = ?;";
			
			ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setInt(1, menuID);
			
			results = ps.executeQuery();
			results.first();

			InputStream is = results.getBlob("menu").getBinaryStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			Object o = null;
			
			try {	
				o = ois.readObject();
			} catch (ClassNotFoundException f) {
				f.printStackTrace();
			} 
			
			Menu m = (Menu) o;
			m.setMenuID(menuID);
			
			//Update menu back
			preparedQuery = "UPDATE IGNORE Menus SET menu = ? WHERE menuID = ?;";
			ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ps.setObject(1, m);
			ps.setInt(2, menuID);
			ps.executeUpdate();
			
		} catch (SQLException f) {
			f.printStackTrace();
		}
		
		response.sendRedirect("MenusTable");
	}
	
	public void establishConnection(){
		
		String dbURL = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbName = "";
		String username = "cs437group01";
		String password = "VHj#dj!v";
		String driver = "com.mysql.jdbc.Driver";
		 
		/*
		String dbURL = "jdbc:mysql://localhost:3306/";
		String dbName = "rcp";
		String username = "root";
		String password = "sesame";
		String driver = "com.mysql.jdbc.Driver";
		*/
		
		try {
			Class.forName(driver).newInstance();
			Nexus.connection = (Connection) DriverManager.getConnection(dbURL + dbName, username, password);
			this.connection = Nexus.connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
